package com.wrial.kind.tree;
/*
 * @Author  Wrial
 * @Date Created in 10:38 2020/8/19
 * @Description 二叉树的锯齿形层次遍历
 *      3
       / \
      9  20
        /  \
       15   7
     [
      [3],
      [20,9],
      [15,7]
     ]

 */

import java.util.*;

public class ZigzagLevelOrder {
    /**
     * 在层次遍历的基础上加一个奇偶标志位
     *
     * @param root
     * @return
     */
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if (root == null) return Collections.emptyList();
        List<List<Integer>> ans = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int flag = 0;//0代表正序 1代表逆序
        while (!queue.isEmpty()) {
            LinkedList<Integer> list = new LinkedList<>();
            int size = queue.size();
            if (flag == 0) {
                for (int i = 0; i < size; i++) {
                    TreeNode node = queue.remove();
                    list.addLast(node.val);
                    if (node.left != null) queue.add(node.left);
                    if (node.right != null) queue.add(node.right);
                }
                flag = 1;
            } else {
                for (int i = 0; i < size; i++) {
                    TreeNode node = queue.remove();
                    list.addFirst(node.val);
                    if (node.left != null) queue.add(node.left);
                    if (node.right != null) queue.add(node.right);
                }
                flag = 0;
            }
            ans.add(list);
        }
        return ans;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}
